package edu.ptu.shortlink.project.dao.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import edu.ptu.shortlink.project.dao.entity.LinkBrowserStatsDO;
import edu.ptu.shortlink.project.dto.req.ShortLinkGroupStatsReqDTO;
import edu.ptu.shortlink.project.dto.req.ShortLinkStatsReqDTO;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.HashMap;
import java.util.List;

/**
 * @BelongsProject: shortlink
 * @BelongsPackage: edu.ptu.shortlink.project.dao.mapper
 * @Author: HYJ
 * @CreateTime: 2025-05-07  06:18
 * @Description: 短链浏览器统计持久层接口
 * @Version: 1.0
 */
public interface LinkBrowserStatsMapper extends BaseMapper<LinkBrowserStatsDO> {
    @Insert("INSERT INTO t_link_browser_stats ( full_short_url, gid, date, cnt, browser, create_time, update_time, del_flag ) "
            + "VALUES (#{linkBrowserStatsDO.fullShortUrl},#{linkBrowserStatsDO.gid},#{linkBrowserStatsDO.date}, #{linkBrowserStatsDO.cnt}, #{linkBrowserStatsDO.browser}, NOW(), NOW(), 0 ) "
            + "ON DUPLICATE KEY UPDATE cnt = cnt + #{linkBrowserStatsDO.cnt}; ")
    void shortLinkBrowserStatsInc(@Param("linkBrowserStatsDO") LinkBrowserStatsDO linkBrowserStatsDO);

    /**
     * 根据短链接获取指定日期内浏览器统计数据
     */
    @Select("SELECT " +
            "    tlbs.browser, " +
            "    SUM(tlbs.cnt) AS count " +
            "FROM " +
            "    t_link tl INNER JOIN " +
            "    t_link_browser_stats tlbs ON tl.full_short_url = tlbs.full_short_url " +
            "WHERE " +
            "    tlbs.full_short_url = #{param.fullShortUrl} " +
            "    AND tl.gid = #{param.gid} " +
            "    AND tl.del_flag = '0' " +
            "    AND tl.enable_status = #{param.enableStatus} " +
            "    AND tlbs.date BETWEEN #{param.startDate} and #{param.endDate} " +
            "GROUP BY " +
            "    tlbs.full_short_url, tl.gid, tlbs.browser;")
    List<HashMap<String, Object>> listBrowserStatsByShortLink(@Param("param") ShortLinkStatsReqDTO requestParam);

    /**
     * 根据分组获取指定日期内浏览器统计数据
     */
    @Select("SELECT " +
            "    tlbs.browser, " +
            "    SUM(tlbs.cnt) AS count " +
            "FROM " +
            "    t_link tl INNER JOIN " +
            "    t_link_browser_stats tlbs ON tl.full_short_url = tlbs.full_short_url " +
            "WHERE " +
            "    tl.gid = #{params.gid} " +
            "    AND tl.del_flag = '0' " +
            "    AND tl.enable_status = '0' " +
            "GROUP BY " +
            "    tlbs.gid, tlbs.browser;")
    List<HashMap<String, Object>> listBrowserStatsByGroup(@Param("params") ShortLinkGroupStatsReqDTO requestParam);
}
